package com.hxd.mall.module.common

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.drawable.Drawable
import android.text.TextUtils
import android.util.Log
import android.view.ViewGroup
import android.webkit.WebView
import androidx.core.content.ContextCompat
import androidx.core.graphics.drawable.toBitmap
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.transition.Transition
import com.hexin.locallibrary.permssion.PermissionGrantedCallback
import com.hexin.locallibrary.permssion.PermissionList
import com.hexin.locallibrary.permssion.PermissionList.permission_sdcardRW
import com.hexin.locallibrary.permssion.PermissionUtils
import com.hexin.locallibrary.permssion.PermissionUtils.permissionCheck
import com.hxd.mall.R
import com.hxd.mall.base.BaseInjectActivity
import com.hxd.mall.constant.HxdConstants.IntentParamsKeyDefine.key_isload_baichuan
import com.hxd.mall.constant.HxdConstants.IntentParamsKeyDefine.key_title_is_use
import com.hxd.mall.constant.HxdConstants.IntentParamsKeyDefine.key_title_name
import com.hxd.mall.constant.HxdConstants.IntentParamsKeyDefine.key_web_url
import com.hxd.mall.constant.HxdConstants.IntentParamsKeyDefine.product_skuNo
import com.hxd.mall.constant.HxdConstants.IntentParamsKeyDefine.web_title_left_type
import com.hxd.mall.constant.HxdConstants.IntentParamsKeyDefine.web_title_right_type
import com.hxd.mall.constant.HxdConstants.TB_auther_isgo
import com.hxd.mall.constant.HxdConstants.Web_Title_Left_Type_Default
import com.hxd.mall.constant.HxdConstants.Web_Title_Left_Type_Finish
import com.hxd.mall.constant.HxdConstants.Web_Title_Right_Type_Show_Finish
import com.hxd.mall.constant.HxdConstantsAccount.token
import com.hxd.mall.constant.HxdConstantsNet.HOST_URL_ONLINE
import com.hxd.mall.constant.HxdConstantsRouterPath.Common.path_to_webview
import com.hxd.mall.constant.HxdConstantsRouterPath.PathAccount.path_login_input_phone
import com.hxd.mall.constant.HxdConstantsRouterPath.Product.path_hxd_product_detail_page
import com.hxd.mall.network.base.BaseRequest
import com.hxd.mall.network.service.ManagerFunctionApi
import com.hxd.mall.network.service.ManagerFunctionApi.mIMeFunctionApi
import com.hxd.mall.utils.local.NavigationUtil.routerNavigation
import com.hxd.mall.utils.local.StackManageUtil.removeActivity
import com.hxd.mall.utils.open.*
import com.hxd.mall.widget.HxdTitleBarView
import com.hxd.threelibrary.baichuan.AlibcClient
import com.hxd.threelibrary.baichuan.AlibcClient.openWebviewByUrl
import com.hxd.threelibrary.baichuan.ShoppingUtils.openTaoBaoApp
import com.hxd.threelibrary.baichuan.ShoppingUtils.oppentb
import com.hxd.threelibrary.getRegistList
import com.hxd.threelibrary.initAll
import com.hxd.threelibrary.umeng.UmClient
import com.hxd.threelibrary.webview.CallBackFunction
import com.hxd.threelibrary.webview.GetRegistAction
import com.hxd.threelibrary.webview.bean.JsBridgeInterfaceBean
import com.hxd.threelibrary.webview.bean.JsBridgeInterfaceParentBean
import com.orhanobut.logger.Logger
import kotlinx.android.synthetic.main.activity_web_view_js_bridge.*
import kotlinx.android.synthetic.main.base_title.*
import org.greenrobot.eventbus.EventBus
import java.net.URI
import java.text.SimpleDateFormat
import java.util.*


/**
 * 共用js_WebView
 */
@Route(path = path_to_webview)
class WebViewJsBridgeCommonActivity : BaseInjectActivity<WebViewPresenter>() {

    private var whiteList = arrayOf("taobao://", "alipayqr://", "alipays://", "wechat://", "weixin://", "mqq://", "mqqwpa://", "openapp.jdmobile://")
    private var mNativeInfo = "getNativeInfoHandler"
    private var mDataFrom = "data from Java"
    private lateinit var mTitleBarView: HxdTitleBarView
    private var mTitleLeftType = 0
    private var mTitleLRightType = 0
    //百川sdk需要特殊加载
    private var isLoadBaiChuan = false
    private var titleName: String = ""
    private val mRequestCode = 9000

    override fun attachLayoutRes() = R.layout.activity_web_view_js_bridge

    @SuppressLint("SetJavaScriptEnabled")
    override fun initViews() {
        titleName = intent.getStringExtra(key_title_name) ?: ""
        val titleUse = intent.getBooleanExtra(key_title_is_use, false)
        isLoadBaiChuan = intent.getBooleanExtra(key_isload_baichuan, false)
        Log.i("title", "titleName=$titleName---titleUse=$titleUse")
        val url: String? = intent.getStringExtra(key_web_url)
        Logger.i("url:$url")
        mTitleLeftType = intent.getIntExtra(web_title_left_type, 0)
        mTitleLRightType = intent.getIntExtra(web_title_right_type, 0)
        setTitle(titleName, titleUse)
        webViewInit(url ?: "", titleUse)
//        webViewInit("http://mall-h5-test.hxvc.com/mainActivity", titleUse)
    }

    override fun initData() {
        val scheme = URI(HOST_URL_ONLINE).scheme
//        val commonMethod = "{\"jsRegisterList\":[" +
//                "{\"scheme\":\"$scheme\",\"target\":\"\",\"action\":\"getCommonParams\",\"transformType\":0}," +
//                "{\"scheme\":\"$scheme\",\"target\":\"\",\"action\":\"goBack\",\"transformType\":0}," +
//                "{\"scheme\":\"$scheme\",\"target\":\"\",\"action\":\"finishPage\",\"transformType\":0}," +
//                "{\"scheme\":\"$scheme\",\"target\":\"\",\"action\":\"setTitle\",\"transformType\":0}," +
//                "{\"scheme\":\"$scheme\",\"target\":\"FaceAuthpage@\\/faceRecognition\\/default\",\"action\":\"nativeFaceAuthViewController@jumpPage\",\"transformType\":0}," +
//                "{\"scheme\":\"$scheme\",\"target\":\"\",\"action\":\"refresh\",\"transformType\":0}]}"
        val bean = JsBridgeInterfaceBean(
            scheme, "FaceAuthpage@/faceRecognition/default", "nativeFaceAuthViewController@jumpPage", 0
        )
        val list = arrayListOf<JsBridgeInterfaceBean>()
        arrayOf(
            "getCommonParams", "goBack", "finishPage", "setTitle",
            "refresh", "toDetail", "autherResult", "openTB", "toAuthorize", "toLogin", "shareText", "shareImg"
        ).forEach {
            list.add(JsBridgeInterfaceBean(scheme, "", it, 0))
        }
        list.add(bean)

        val parentBean = JsBridgeInterfaceParentBean().apply { jsRegisterList = list }
        getRegistList(parentBean, web_view_js_bridge, object : GetRegistAction {
            override fun nativeJumpPage(path: String?) {
                if (!TextUtils.isEmpty(path)) {
                    routerNavigation(path!!)
                }
            }

            override fun nativeExecMethod(
                action: String?,
                target: String?,
                function: CallBackFunction?
            ) {
                dealAction(action, function, target)
            }
        })
    }

    override fun onDestroy() {

        //EventBus.getDefault().unregister(this)

        web_view_js_bridge.run {
            (this.parent as ViewGroup).removeView(this)
            this.destroy()
            layout_common_web_view_layout.removeView(this)
        }
        super.onDestroy()

    }

    override fun onBackPressed() = goBack()

    /**
     * 回退策略
     */
    private fun goBack() {

        if (isLoadBaiChuan) {
            //如果是阿里百川的授权需要关掉当前界面
            removeActivity(this)
            return
        }
        if (web_view_js_bridge.canGoBack()) {
            web_view_js_bridge.goBack()
        } else {
            super.onBackPressed()
        }
    }

    //初始化
    private fun webViewInit(url: String, titleUse: Boolean) {
        //头布局参数
        val headerMap = mutableMapOf(
            "Authorization" to (if (token == null) "" else token ?: "")
        )

        //配置初始化
        initAll(
            web_view_js_bridge,
            url,
            HxdTitleBarView(this).getTitleTextView(),
            web_bar,
            titleUse,
            URI(HOST_URL_ONLINE).host,
            whiteList,
            headerMap
        )

        //webView长按事件
        web_view_js_bridge.setOnLongClickListener {
            val hitTestResult = (it as WebView).hitTestResult
                ?: return@setOnLongClickListener false
            when (hitTestResult.type) {
                WebView.HitTestResult.IMAGE_TYPE -> {
                    if (hitTestResult.extra == null) {
                        return@setOnLongClickListener false
                    }
                    val imgData = hitTestResult.extra
                    if (TextUtils.isEmpty(imgData))
                        return@setOnLongClickListener false
                    FileUtil.base64StrToImage(imgData!!)
                    ToastUtil.showToast("保存图片成功..")
                }
            }
            false
        }

        if (isLoadBaiChuan) {
            //百川sdk需要通过openUrl方法加载
            url.let { openWebviewByUrl(this, it, web_view_js_bridge, web_bar, tv_title_name) }
        }
    }

    /**
     * @param action
     * @param target
     * @param function js交互
     */
    private fun dealAction(action: String?, function: CallBackFunction?, target: String?) {
        when (action) {
            "getCommonParams" -> {
//                function?.onCallBack("{\"token\":\"$token\"}")
                function?.onCallBack(token ?: "")
            }
            "goBack" -> {
                goBack()
                function?.onCallBack("")
            }
            "finishPage" -> {
                removeActivity(this@WebViewJsBridgeCommonActivity)
                function?.onCallBack("")
            }
            "setTitle" -> {
                if (!TextUtils.isEmpty(target)) {
                    mTitleBarView.setTitleName(target!!)
                }
                function?.onCallBack("")
            }
            "refresh" -> {
                web_view_js_bridge.loadUrl("javascript:window.history.go(-(window.history.length - 1))")
                function?.onCallBack("")
            }
            "toDetail" -> {
                if (!TextUtils.isEmpty(target)) {
                    routerNavigation(path_hxd_product_detail_page, mutableMapOf(product_skuNo to target!!))
                }
            }
            "autherResult" -> {
                //淘宝认证结果
                if (!TextUtils.isEmpty(target)) {
                    val auther = GsonUtil.json2bean(target!!, AutherBean::class.java)
                    //通知首页和商品详情页刷新
                    EventBus.getDefault().post(AutherBean(auther.code == 0))
                    val msg = when (auther.code) {
                        0 -> "授权成功"
                        6012, 1005, 15 -> auther.msg
                        else -> "授权失败"
                    }
                    Log.i("auther_msg", target)
                    ToastUtil.showToast(msg ?: "")
//                    removeActivity(this@WebViewJsBridgeCommonActivity)
                    finish()
                }
            }
            "openTB" -> {
                if (!TextUtils.isEmpty(target)) {
                    openTaoBaoApp(this,"粉丝服务购",target)
                    /*oppentb(this, target) {
                        routerNavigation(path_to_webview, key_web_url, it)
                    }*/
                }
            }
            // 去授权
            "toAuthorize" -> {
                //未授权 通知首页去获取授权的url
                //EventBus.getDefault().post(AutherBean(false, 0))
                if (!TB_auther_isgo) {
                    ToastUtil.showToast("授权太频繁啦，休息一会儿再试吧")
                    return
                }
                //showLoading()
                //授权操作
                AlibcClient.login { _, flag ->
                    if (!flag) {
                        TB_auther_isgo = flag
                        //hideLoading()
                    }
                    ARouter.getInstance().build(path_to_webview).withString(key_web_url, (target ?: "")).withBoolean(key_isload_baichuan , true).navigation(this, mRequestCode)
//                    routerNavigation(path_to_webview, mutableMapOf(key_web_url to (target ?: ""), key_isload_baichuan to true))
                }
            }
            //去登陆
            "toLogin" -> {
                //从登陆也回来后刷新界面
                ARouter.getInstance().build(path_login_input_phone).navigation(this, mRequestCode)
            }
            "shareText" -> {
                if (!TextUtils.isEmpty(target))
                    UmClient.shareText(this, UmClient.WEIXIN, target ?: "") {}
            }
            "shareImg" -> {
                showLoading()
                //从接口取图片和邀请码，然后分享到微信
                BaseRequest.request(mIMeFunctionApi.posterPage, {
                    if (it?.data?.bgImgList != null && it.data.bgImgList.isNotEmpty()) {
                        Glide.with(this@WebViewJsBridgeCommonActivity).load(it.data.bgImgList[0]).into(object : SimpleTarget<Drawable>() {
                            override fun onResourceReady(resource: Drawable, transition: Transition<in Drawable>?) {
                                hideLoading()
                                showShareFriendDialog { type ->
                                    when (type) {
                                        UmClient.WEIXIN, UmClient.WEIXIN_CIRCLE -> {
                                            val bitmap = AddTimeWatermark(resource.toBitmap(), it.data.invitationCode)
                                            //这里会打开微信界面，会有点慢，因此在界面的onStop里关闭
                                            showLoading()
                                            UmClient.shareScreenShot(this@WebViewJsBridgeCommonActivity, type, bitmap) {}
                                        }
                                        UmClient.SAVE_PIC -> {
                                            permissionCheck(this@WebViewJsBridgeCommonActivity, permission_sdcardRW, "", object : PermissionGrantedCallback {
                                                override fun granted() {
                                                    val bitmap = AddTimeWatermark(resource.toBitmap(), it.data.invitationCode)
                                                    saveBitmap(bitmap, this@WebViewJsBridgeCommonActivity)
                                                }

                                                override fun denied() {
                                                }
                                            })
                                        }
                                    }
                                }
                            }
                        })
                    } else {
                        ToastUtil.showToast("暂未获取到图片")
                        hideLoading()
                    }
                }, {
                    hideLoading()
                    ToastUtil.showToast(it.msg ?: "")
                })
            }
        }
    }


    override fun onStop() {
        super.onStop()
        hideLoading()
    }

    //设置标题
    private fun setTitle(titleName: String, titleUse: Boolean) {
        mTitleBarView = setTitleCommon(if (titleUse) titleName else "") {
            when (mTitleLeftType) {
                Web_Title_Left_Type_Default -> goBack()
                Web_Title_Left_Type_Finish -> removeActivity(this)
            }
        }
        if (mTitleLRightType == Web_Title_Right_Type_Show_Finish) {
            mTitleBarView.setTitleRightJustText(text = "关闭").setOnRightClickedListener {
                removeActivity(this)
            }
        }
    }

    private fun AddTimeWatermark(mBitmap: Bitmap, text: String): Bitmap {
        //获取原始图片与水印图片的宽与高
        val mBitmapWidth = mBitmap.width
        val mBitmapHeight = mBitmap.height
        val mNewBitmap = Bitmap.createBitmap(mBitmapWidth, mBitmapHeight, Bitmap.Config.ARGB_8888)
        val mCanvas = Canvas(mNewBitmap)
        //向位图中开始画入MBitmap原始图片
        mCanvas.drawBitmap(mBitmap, 0f, 0f, null)
        //添加文字
        val mPaint = Paint()
        mPaint.color = Color.WHITE
        mPaint.textSize = 30f
        //水印的位置坐标
        mCanvas.drawText(text, ((mBitmapWidth - 114) / 2).toFloat(), (mBitmapHeight - 50).toFloat(), mPaint)
        mCanvas.save()
        mCanvas.restore()
        return mNewBitmap
    }

    //从登陆也回来后刷新
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == mRequestCode) {
            web_view_js_bridge.reload()
        }
    }
}
